import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 创建仓库实例
const store = new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  getters: {
    totalNum (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.num
        }
        return sum
      }, 0)
    },
    totalPrice (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.num * item.price
        }
        return sum
      }, 0)
    }
  },
  mutations: {
    removeItem (state, index) {
      state.goodList.splice(index, 1)
    },
    changeNum (state, payload) {
      state.goodList[payload.index].num += payload.num
    },
    changeState (state, index) {
      state.goodList[index].checked = !state.goodList[index].checked
    },
    changeAll (state, val) {
      state.goodList.forEach(item => { item.checked = val })
      // console.log(val)
    }
  }

})
// 导出实例
export default store
